package mysql_9_18;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectDao {
	private static Properties configFile = new Properties();
	protected static final Logger logger = LoggerFactory.getLogger(ConnectDao.class);
	static {
		try {
			configFile.load(ConnectDao.class.getClassLoader().getResourceAsStream("Config.properties"));
			Class.forName(configFile.getProperty("driver"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
			System.exit(1);
		}
	}

	public Connection getConnection() {
		try {
			return DriverManager.getConnection(configFile.getProperty("url"), configFile.getProperty("name"),
					configFile.getProperty("pw"));
		} catch (SQLException e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
			throw new RuntimeException(e);
		}
	}

	public void closeAll(Connection con, Statement st, ResultSet rs) {
		close(rs);
		close(st);
		close(con);
	}

	public void close(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
		}

	}

	public void close(Statement st) {
		try {
			if (st != null) {
				st.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
		}

	}

	public void close(Connection con) {
		try {
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
		}

	}

	public <T extends Serializable> ArrayList<T> search(String sql, Class<T> t, Object... objects) {
		ArrayList<T> datas = new ArrayList<T>();
		Connection con = getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = con.prepareStatement(sql);
			for (int i = 0; i < objects.length; i++) {
				st.setObject(i + 1, objects[i]);
			}
			rs = st.executeQuery();
			ResultSetMetaData rm = rs.getMetaData();
			while (rs.next()) {
				T obj = t.newInstance();
				for (int i = 0; i < rm.getColumnCount(); i++) {
					String field = rm.getColumnLabel(i + 1);
					Field f = t.getDeclaredField(field);
					f.setAccessible(true);
					f.set(obj, rs.getObject(i + 1));
				}
				datas.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
		} finally {
			closeAll(con, st, rs);
		}
		return datas;
	}
}
